//
//  ChangePasswordViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/12/14.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

class ChangePasswordViewController: UIViewController, UITextFieldDelegate {

    
    @IBOutlet weak var button: UIButton!

    @IBOutlet weak var buttonLayoutConstraint: NSLayoutConstraint!
    
    
    let userAuthVM = UserAuthViewModel.shared
    
    let disposeBag = DisposeBag()
    
    var totpResult: TOTPAuthResult?
    
    let authManager = AuthManager.share
    
    let backButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "back_black"), for: .normal)
        return button
    }()
    
    let titleLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 24)
        label.textColor = UIColor.gray
        label.text = LanguageHelper.getString(key: "CHANGE_PASSWORD")
        return label
    }()
    
    let descriptionLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 14)
        label.textColor = lightTextColor
        label.text = LanguageHelper.getString(key: "SET_NEW_PASSWORD")
        return label
    }()
    
    let passwdTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = LanguageHelper.getString(key: "TYPE_NEW_PASSWORD") 
        textField.font = AppFont(size: 15)
        textField.isSecureTextEntry = true
        return textField
    }()
    
    let passwdSaperator: UIView = {
        let view = UIView()
        view.backgroundColor = saperatorColor
        return view
    }()
    
    let passwdConfirmTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = LanguageHelper.getString(key: "CONFIRM_NEW_PASSWORD")
        textField.font = AppFont(size: 15)
        textField.isSecureTextEntry = true
        return textField
    }()
    
    let passwdConfirmSaperator: UIView = {
        let view = UIView()
        view.backgroundColor = saperatorColor
        return view
    }()
    
    var alertController: UIAlertController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        button.layer.cornerRadius = 3
        button.layer.masksToBounds = true
        
        backButton.frame = CGRect(x: 15, y: 35, width: 22, height: 22)
        backButton.addTarget(self, action: #selector(backForButton(_:)), for: .touchUpInside)
        
        let leading: CGFloat = 45
        
        let textMaxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleSize = TextSize.textSize(text: titleLabel.text!, font: titleLabel.font, maxSize: textMaxSize)
        titleLabel.frame = CGRect(x: leading, y: 85, width: titleSize.width, height: titleSize.height)
        let descriptionSize = TextSize.textSize(text: descriptionLabel.text!, font: descriptionLabel.font, maxSize: textMaxSize)
        descriptionLabel.frame = CGRect(x: leading, y: titleLabel.frame.origin.y + titleLabel.frame.height + 8, width: descriptionSize.width, height: descriptionSize.height)
        
        var currentY = descriptionLabel.frame.origin.y + descriptionLabel.frame.height
        
        passwdTextField.frame = CGRect(x: leading, y: currentY + 30, width: self.view.bounds.width - CGFloat(2) * leading, height: 25)
        
        currentY = passwdTextField.frame.origin.y + passwdTextField.frame.height
        
        passwdSaperator.frame = CGRect(x: leading, y: currentY + 8, width: self.view.bounds.width - CGFloat(2) * leading, height: 0.5)
        
        currentY = passwdSaperator.frame.origin.y + passwdSaperator.frame.height
        
        passwdConfirmTextField.frame = CGRect(x: leading, y: currentY + 30, width: self.view.bounds.width - CGFloat(2) * leading, height: 25)
        
        currentY = passwdConfirmTextField.frame.origin.y + passwdConfirmTextField.frame.height
        
        passwdConfirmSaperator.frame = CGRect(x: leading, y: currentY + 8, width: self.view.bounds.width - CGFloat(2) * leading, height: 0.5)
        
        currentY = passwdConfirmSaperator.frame.origin.y + passwdConfirmSaperator.frame.height
        
        buttonLayoutConstraint.constant = currentY + 45
        
        currentY = currentY + 45 + button.frame.height
        
        button.isEnabled = false
        
        self.passwdTextField.delegate = self
        self.passwdConfirmTextField.delegate = self
        
        self.passwdTextField.addTarget(self, action: #selector(textFieldValueChange(_:)), for: .editingChanged)
        
        self.passwdConfirmTextField.addTarget(self, action: #selector(textFieldValueChange(_:)), for: .editingChanged)
        
        button.addTarget(self, action: #selector(change(_:)), for: .touchUpInside)
        
        alertController = UIAlertController(title: LanguageHelper.getString(key: "CHANGE_PW_SUCCESS"),
            message: nil, preferredStyle: .alert)
        let okAction = UIAlertAction(title: LanguageHelper.getString(key: "GO_SIGNIN"), style: .cancel, handler: {
            action in
            self.dismiss(animated: true, completion: nil)
        })
        alertController.addAction(okAction)
        
        self.view.addSubview(backButton)
        self.view.addSubview(titleLabel)
        self.view.addSubview(descriptionLabel)
        self.view.addSubview(passwdTextField)
        self.view.addSubview(passwdSaperator)
        self.view.addSubview(passwdConfirmTextField)
        self.view.addSubview(passwdConfirmSaperator)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let point = touch.location(in: self.view)
            if !self.passwdTextField.frame.contains(point) && !self.passwdConfirmTextField.frame.contains(point) {
                self.passwdTextField.resignFirstResponder()
                self.passwdConfirmTextField.resignFirstResponder()
            }
        }
    }
    
    func textFieldValueChange(_ sender: UITextField) {
        if self.passwdTextField.text != "" && self.passwdConfirmTextField.text != "" {
            self.button.isEnabled  = true
        } else {
            self.button.isEnabled = false
        }
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self.passwdConfirmTextField {
            passwdConfirmSaperator.backgroundColor = UIColor.black
        } else {
            passwdSaperator.backgroundColor = UIColor.black
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == self.passwdConfirmTextField {
            passwdConfirmSaperator.backgroundColor = saperatorColor
        } else {
            passwdSaperator.backgroundColor = saperatorColor
        }
    }
    
    func change(_ sender: UIButton) {
        self.passwdTextField.resignFirstResponder()
        self.passwdConfirmTextField.resignFirstResponder()
        if passwdTextField.text != passwdConfirmTextField.text {
            self.showPromptView(message: LanguageHelper.getString(key: "PASSWORD_DIFF"), confirmText: LanguageHelper.getString(key: "OK"))
        } else if (passwdTextField.text?.count)! < 4 {
            self.showPromptView(message: LanguageHelper.getString(key: "AT_LEAST4"), confirmText: LanguageHelper.getString(key: "OK"))
        } else {
            let newPW = passwdTextField.text!.trim()
            userAuthVM.changePW(newPW: newPW, token: (totpResult?.token)!).subscribe(onNext: { [unowned self] response in
                if let con = response.success {
                    if con {
                        self.present(self.alertController, animated: true, completion: nil)
                    } else {
                        self.showPromptView(message: response.data!, confirmText: LanguageHelper.getString(key: "OK"))
                    }
                } else {
                    self.showPromptView(message: LanguageHelper.getString(key: "ERROR_OCCUR"), confirmText: LanguageHelper.getString(key: "OK"))
                }                
            })
            .addDisposableTo(disposeBag)
        }        
    }
}
